﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using pc_system.Model;
using PosTest;
using System.Text.RegularExpressions;

namespace pc_system.View
{
    public partial class main_new : Form
    {
        dbEntities _db;
        vClientInfo vcif;
        CustomPos pos = new CustomPos(GlobalVariables.POS_PORT);
       
        public main_new()
        {

            Form1 f = new Form1();
            Form1 formLogin = new Form1();
            if (formLogin.ShowDialog() != DialogResult.OK)
            {
                Environment.Exit(Environment.ExitCode);
                return;
            }
            InitializeComponent();
            submit_order_button.MouseClick += submitOrder;
            button8.Click += btnAddClinet;
            main_tabcontrol.SelectedIndexChanged += main_tabcontrol_SelectedIndexChanged;
            dataGridView3.CurrentCellChanged += dataGridView3_CurrentCellChanged;
            textBox3.KeyPress += textBox3_KeyPress;
            textBox2.KeyPress += addBuyOrder;
            button1.Click += updata_textbox;
            dataGridView5.CellEndEdit += editProduct;
            dataGridView2.DataError += dataGridView3_DataError;
            dataGridView5.DataError += dataGridView3_DataError;
            button6.Click += delBuyGridViewColumn;
            button14.Click += show_info;
            button2.Click += btn_submitBuy_Click;
            dataGridView2.CellEndEdit += updateBuyGridView;
            button13.Click += show_info;
            button12.Click += show_info;
            settings_com.TextChanged += settings_com_TextChanged;
            button3.Click += button3_Click;
            dataGridView6.DataSourceChanged += dataGridView6_DataSourceChanged;
            //单据退货
            danju_tuihuo.Click += danju_tuihuo_Click;
        }

        void danju_tuihuo_Click(object sender, EventArgs e)
        {
            vSaleHistoryDetails sd = (vSaleHistoryDetails) dataGridView6.CurrentRow.DataBoundItem;
            if (DBFunc.returnGood(sd.detail_id) == true)
            {
                MessageBox.Show("退货处理成功");
            }
            else
            {
                MessageBox.Show("退货失败，是否已经退货");
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _db = new dbEntities();
            this.storesBindingSource.DataSource = _db.stores;
            Bind_combox();
            settings_com.Text = GlobalVariables.POS_PORT;
            this.salehistoryBindingSource.DataSource = _db.salehistory.OrderByDescending(c => c.order_id);
            pos = new CustomPos(GlobalVariables.POS_PORT);
            pos.Init();
        } 


        private void setColumnsType()
        {
            this.BarCode.ValueType = typeof(string);
            this.PdName.ValueType = typeof(string);
            this.SalePrice.ValueType = typeof(float);
            this.Discount.ValueType = typeof(int);
            this.Count.ValueType = typeof(int);
            this.Price.ValueType = typeof(float);
            this.SubTotal.ValueType = typeof(float);
            this.jinBarcode.ValueType = typeof(string);
            this.jinCount.ValueType = typeof(int);
            this.jinPdName.ValueType = typeof(string);
            this.jinPrice.ValueType = typeof(float);
            //updateGridView();
        }

        private void main_new_Load(object sender, EventArgs e)
        {
           //  this.WindowState = FormWindowState.Maximized;
            setColumnsType();
        }

        #region 按钮变色
        private void button3_MouseEnter(object sender, EventArgs e)
        {
            nav_salerecord.BackgroundImage = Resource1.销售单据h;
        }

        private void nav_productget_MouseEnter(object sender, EventArgs e)
        {
            nav_productget.BackgroundImage = Resource1.订货h;
        }

        private void nav_productget_MouseLeave(object sender, EventArgs e)
        {
            nav_productget.BackgroundImage = Resource1.订货f;
        }

        private void nav_jiaojieban_MouseEnter(object sender, EventArgs e)
        {
            nav_jiaojieban.BackgroundImage = Resource1.交接班h;
        }

        private void nav_jiaojieban_MouseLeave(object sender, EventArgs e)
        {
            nav_jiaojieban.BackgroundImage = Resource1.交接班f;
        }

        private void nav_addclient_MouseEnter(object sender, EventArgs e)
        {
            nav_addclient.BackgroundImage = Resource1.新增会员h;
        }

        private void nav_addclient_MouseLeave(object sender, EventArgs e)
        {
            nav_addclient.BackgroundImage = Resource1.新增会员f;
        }

        private void nav_salerecord_MouseLeave(object sender, EventArgs e)
        {
            nav_salerecord.BackgroundImage = Resource1.销售单据f;
        }

        private void nav_productedit_MouseEnter(object sender, EventArgs e)
        {
            nav_productedit.BackgroundImage = Resource1.商品编辑h;
        }

        private void nav_productedit_MouseLeave(object sender, EventArgs e)
        {
            nav_productedit.BackgroundImage = Resource1.商品编辑f;
        }

        private void nav_gouwu_MouseEnter(object sender, EventArgs e)
        {
            nav_gouwu.BackgroundImage = Resource1.购物h;
        }

        private void nav_gouwu_MouseLeave(object sender, EventArgs e)
        {
            nav_gouwu.BackgroundImage = Resource1.购物f;
        }

        private void nav_salerecord_MouseEnter(object sender, EventArgs e)
        {
            nav_salerecord.BackgroundImage = Resource1.销售单据h;
        }

        private void nav_settings_MouseEnter(object sender, EventArgs e)
        {
            nav_settings.BackgroundImage = Resource1.系统设置h;
        }

        private void nav_settings_MouseLeave(object sender, EventArgs e)
        {
            nav_settings.BackgroundImage = Resource1.系统设置f;
        }

        #endregion



        #region 添加购物车
        /// <summary>
        /// 购物条码输入框处理 不检查库存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != (Char)Keys.Enter) return;
            _db = new dbEntities();
            TextBox tb = (TextBox)sender;
            //TODO: 其他分店有，本分店无的情况
            var pd = _db.vProduct.FirstOrDefault(c => c.product_code == tb.Text &&
                c.store_id == GlobalVariables.STORE_ID);
            if (pd == null) 
            {
                SystemInfo f = new SystemInfo("找不到商品","是否添加",2);
                if(f.ShowDialog() == DialogResult.OK)
                {
                    ProductInfo pf = new ProductInfo(rcode.Text);
                    if (pf.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
            if (pd.total_count == null || pd.total_count < 1)
            {
                MessageBox.Show("库存不足");
                return;
            }
            else
            {
                addPdToGridView(rcode.Text);
            }
            updateGridView();
            tb.Text = "";
            tb.SelectAll();
        }

        private void addPdToGridView(string rcode)
        {
            _db = new dbEntities();
            DataGridViewRow dgvr = new DataGridViewRow();
            var pd = _db.vProduct.FirstOrDefault(c => c.product_code == rcode &&
                c.store_id == GlobalVariables.STORE_ID);
            foreach (DataGridViewRow dr in dataGridView1.Rows)
            {
                if((string)dr.Cells["BarCode"].Value == pd.product_code &&
                    (int)dr.Cells["Discount"].Value == pd.discount)
                {
                    dr.Cells["Count"].Value = (int)dr.Cells["Count"].Value + 1;
                    return;
                }
            }
            dataGridView1.Rows.Add(pd.product_code, pd.product_name, pd.sale_prices, pd.discount, 1);
        }

        private float updateGridView()
        {
            float total_price = 0.0f;
            int total_count = 0;
            //if (dataGridView1.Rows.Count < 1) return 0.0f;
            foreach (DataGridViewRow dr in dataGridView1.Rows)
            {
                dr.Cells["Price"].Value = (int)dr.Cells["Discount"].Value * (float)dr.Cells["SalePrice"].Value / 100;
                dr.Cells["SubTotal"].Value = (float)dr.Cells["Price"].Value * (int)dr.Cells["Count"].Value;
                total_count += (int)dr.Cells["Count"].Value;
                total_price += (float)dr.Cells["SubTotal"].Value;
            }
            label5.Text = total_count.ToString() + " 件商品";
            submit_order_button.Text = "￥" + total_price.ToString();
            rcode.Focus();
            pos.SetDisplayMode(CustomPos.DisplayMode.Total);
            pos.Display(total_price.ToString("0.00"));
            return total_price;
        }


        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 5)
            {
                DataGridView dgv = (DataGridView)sender;
                DataGridViewRow dgvr = dgv.Rows[e.RowIndex];
                dgvr.Cells["Discount"].Value = (int)((float)dgvr.Cells["Price"].Value / (float)dgvr.Cells["SalePrice"].Value *100);
            }
            updateGridView();
        }

        private void del_productbtn_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null) return;
            dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
            //TODO: DataView统一绑定数据源
            updateGridView();
        }

        #region 提交订单
        private void submitOrder(object sender, MouseEventArgs e)
        {
            if (dataGridView1.Rows.Count < 1) return;
            saleFinal sf = new saleFinal(updateGridView());
            if (sf.ShowDialog() != DialogResult.OK) return;
            dbEntities db = new dbEntities();
            salehistory sh = new salehistory();
            string[] plist;
            sh.client_id = GlobalVariables.CLIENT_ID;
            sh.staff_id = GlobalVariables.STAFF_ID;
            sh.store_id = GlobalVariables.STORE_ID;
            sh.order_time = DateTime.Now;
            sh.pay_method = sf.PayKind;
            sh.order_amount = updateGridView();
            db.AddTosalehistory(sh);
            db.SaveChanges();

            plist = new string[dataGridView1.Rows.Count*2];
            int i = 0;
            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                string bcode = (string)r.Cells["Barcode"].Value;
                int count = (int)r.Cells["Count"].Value;
                float fPrice = (float)r.Cells["Price"].Value;
                float aPrice = (float)r.Cells[6].Value;
                DBFunc.commitOrder(bcode, count, fPrice, sh.order_id);
                plist[i] = (string)r.Cells[1].Value;
                plist[i + 1] = fPrice.ToString("0.00") + " " + count + " " + aPrice.ToString("0.00");
                i += 2;
            }
            try
            {
                //TODO: 设置打印机
                new Printer(sh.serial_number, plist, sf.PayKind, sf.Ftotal, sf.Shou).printer();
            }
            catch(Exception)
            {
                MessageBox.Show("小票打印失败");
            }
            dataGridView1.Rows.Clear();
            updateGridView();
            updateClientInfo();
            rcode.Text = "输入商品条码";
            rcode.SelectAll();
            usercode.Text = "会员编号/手机号";
            GlobalVariables.CLIENT_ID = 0;
            GlobalVariables.ADDED_ORDERS = true;
        }
        #endregion

        #endregion

        #region 查询会员输入框
        void updateClientInfo()
        {
            label1.Text = "来宾";
            label3.Text = "￥0.00";
            label6.Text = "0";
        }
        void updateClientInfo(string clientcode)
        {
            Int64 id = 0;
            if (!Int64.TryParse(clientcode, out id))
            {
                MessageBox.Show("请输入正确的手机/会员号");
                return;
            }
            dbEntities db = new dbEntities();
            vcif = db.vClientInfo.FirstOrDefault(c => c.client_storeid == DBFunc.STOREID && (c.client_phone == clientcode || c.client_id == id));
            if (vcif == null)
            {
                MessageBox.Show("查无此人");
                return;
            }
            GlobalVariables.CLIENT_ID = vcif.client_id;
            label1.Text = vcif.client_name;
            label3.Text = vcif.client_money.ToString("0.00");
            label6.Text = vcif.client_credit.ToString();
        }

        private void findUser_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox tb = (TextBox)sender;
            if (e.KeyChar == (char)Keys.Enter)
            {
                updateClientInfo(tb.Text);
                tb.SelectAll();
            }
        }
        #endregion
        

        #region 顶部按钮切换 交接班
        private void nav_gouwu_Click(object sender, EventArgs e)
        {
            main_tabcontrol.SelectedTab = main_tabcontrol.TabPages[0];
        }
        private void nav_addclient_Click(object sender, EventArgs e)
        {
            main_tabcontrol.SelectedTab = main_tabcontrol.TabPages[1];
        }
        private void nav_salerecord_Click(object sender, EventArgs e)
        {
            main_tabcontrol.SelectedTab = main_tabcontrol.TabPages[2];
        }

        private void nav_productget_Click(object sender, EventArgs e)
        {
            main_tabcontrol.SelectedTab = main_tabcontrol.TabPages[3];
        }

        private void nav_productedit_Click(object sender, EventArgs e)
        {
            main_tabcontrol.SelectedTab = main_tabcontrol.TabPages[4];
        }

        private void nav_settings_Click(object sender, EventArgs e)
        {
            main_tabcontrol.SelectedTab = main_tabcontrol.TabPages[5];
        }

        #region 交接班
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Form1 f = new Form1();
                this.Hide();
                if (f.ShowDialog() != DialogResult.OK)  //不成功则退出
                {
                    Environment.Exit(Environment.ExitCode);
                    return;
                }
                this.Show();
            }
            catch (System.InvalidOperationException)
            {
                MessageBox.Show("交接班成功");
            }
            main_tabcontrol.SelectedTab = main_tabcontrol.TabPages[0];
        }
        #endregion
#endregion

        #region 标签页选择处理
        void main_tabcontrol_SelectedIndexChanged(object sender, EventArgs e)
        {
            _db = new dbEntities();
            TabControl tbMain = (TabControl)sender;
            tbMain = (TabControl)sender;
            switch (tbMain.SelectedIndex)
            {
                case 0:
                    rcode.Focus();
                    rcode.SelectAll();
                    break;
                case 1:
                    addclient_name.Focus();
                    break;
                case 2:
                    if (GlobalVariables.ADDED_ORDERS == true)
                    {
                        this.salehistoryBindingSource.DataSource = _db.salehistory.OrderByDescending(c => c.order_id);
                        GlobalVariables.ADDED_ORDERS = false;
                    }
                    break;
                case 3:
                    textBox2.Focus();
                    textBox2.SelectAll();
                    break;
                case 4:
                    if (GlobalVariables.ADDED_PRODUCTS == true)
                    {
                        this.vProductInfoBindingSource.DataSource = _db.vProductInfo;
                        GlobalVariables.ADDED_PRODUCTS = false;
                    }
                    textBox3.Focus();
                    textBox3.SelectAll();
                    break;
                case 5:
                    
                    break;


            }
        }
        #endregion

        #region 增加会员
        private void btnAddClinet(object sender, EventArgs e)
        {
            string s="^[0-9]*$";     //验证手机号码只能是11位数字的正则表达式
            string s1 = "^[A-Za-z]+$"; //匹配英文名
            string s2 = "\u4E00-\u9fa5"; //匹配中文名
            Regex reg = new Regex(s);
            Regex reg1 = new Regex(s1);
            Regex reg2 = new Regex(s2);
            if (addclient_name.Text == "") //名字不能为空
            {
                MessageBox.Show("会员姓名不能为空","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                addclient_name.Focus();
                return;
            }

            if (!reg1.IsMatch(addclient_name.Text) || (reg2.IsMatch(addclient_name.Text))) //只接受中文名或者英文名
            {
                MessageBox.Show("请输入中文名或者英文名","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                addclient_name.Text = "";
                addclient_name.Focus();
                return;
            }

            if ((addclient_phone.Text.Count() < 11) || (!reg.IsMatch(addclient_phone.Text))) //只接受11位数字手机号码
            {
                MessageBox.Show("手机号码输入不规范,请输入11位手机号","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                addclient_phone.Text = "";
                addclient_phone.Focus();
                return;
            }

            if (DBFunc.addClient(addclient_name.Text, DateTime.Now, addclient_phone.Text, addclient_introname.Text, addclient_beizhu.Text))
            {
                MessageBox.Show("添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                addclient_name.Text = "";
                addclient_birthdate.Text = "";
                addclient_phone.Text = "";
                addclient_introname.Text = "";
                addclient_beizhu.Text = "";
                this.main_tabcontrol.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("添加失败，请检查你的输入","提示",MessageBoxButtons.OK,MessageBoxIcon.Stop);
            }
            
        }
        #endregion

        #region 增加订货
        /// <summary>
        /// 商品添加条码输入框处理
        /// </summary>
        private void addBuyOrder(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != (Char)Keys.Enter) return;
            _db = new dbEntities();
            TextBox tb = (TextBox)sender;
            addPdToBuyGridView(tb.Text);
            updateBuyGridView();
            tb.SelectAll();
        }

        /// <summary>
        /// 将入库商品加到 DataGridView2
        /// </summary>
        /// <param name="pcode">商品条码</param>
        private void addPdToBuyGridView(string pcode)
        {
            DataGridViewRow dgvr = new DataGridViewRow();
            float _cost = 0.0f;
            foreach (DataGridViewRow dr in dataGridView2.Rows)
            {
                if ((string)dr.Cells[0].Value == pcode)
                {
                    dr.Cells[3].Value = (int)dr.Cells[3].Value + 1;
                    return;
                }
            }
            _db = new dbEntities();
            products_info pd = _db.products_info.FirstOrDefault(c => c.product_code == pcode);
            if (pd == null)
            {
                SystemInfo f = new SystemInfo("找不到商品", "是否添加", 2);
                if (f.ShowDialog() == DialogResult.OK)
                {
                    ProductInfo pf = new ProductInfo(pcode,1);
                    if (pf.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                    else  //添加成功
                    {
                        _cost = pf.Cost;
                        pd = _db.products_info.FirstOrDefault(c => c.product_code == pcode);
                }
                }
                else
                {
                    return;
                }
            }
            else
            {
                pd = _db.products_info.FirstOrDefault(c => c.product_code == pcode);
                var pis = _db.product_in_stock.FirstOrDefault(c => c.product_id == pd.product_id);
                //如果没有进价
                if (pis == null)
                {
                    var pos = _db.product_onsale.FirstOrDefault(c => c.product_id == pd.product_id && c.store_id == GlobalVariables.STORE_ID);
                    //如果没有售价
                    if (pos == null)
                    {
                        ProductInfo pf = new ProductInfo(pcode, pd.product_name);
                        if (pf.ShowDialog() != DialogResult.OK)
                        {
                            return;
                        }
                        _cost = pf.Cost;
                }
                    else
            {
                        ProductInfo pf = new ProductInfo(pcode, pd.product_name, (float)pos.sale_prices);
                        if (pf.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                        _cost = pf.Cost;

                    }
                }
                else  //如果有进价
                {
                    _cost = pis.cost_price;
                }

            }


            dataGridView2.Rows.Add(pd.product_code, pd.product_name, _cost, 1);
        }

        /// <summary>
        /// 重新计算商品总价 DataGridView2
        /// </summary>
        private float updateBuyGridView()
        {
            float total_price = 0.0f;
            int total_count = 0;
            foreach (DataGridViewRow dr in dataGridView2.Rows)
            {
                total_count += (int)dr.Cells[3].Value;
                total_price += (float)dr.Cells[2].Value * (int)dr.Cells[3].Value;
            }
            label15.Text = total_count.ToString() + " 件商品";
            jinhuo_total.Text = total_count.ToString();
            jinhuo_jinjia.Text = " ￥" + total_price.ToString(); 
            textBox2.Focus();
            dataGridView2.ClearSelection();
            return total_price;
        }

        /// <summary>
        /// 删除选中的商品 DataGridView2
        /// </summary>
        private void delBuyGridViewColumn(object sender, EventArgs e)
        {
            if (dataGridView2.CurrentRow == null) return;
            dataGridView2.Rows.Remove(dataGridView2.CurrentRow);
            updateBuyGridView();
        }

        /// <summary>
        /// 提交进货到数据库 Button2
        /// </summary>
        private void btn_submitBuy_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            updateBuyGridView();
            if (dataGridView2.Rows.Count < 1) return;
            foreach (DataGridViewRow r in dataGridView2.Rows)
            {
                string bcode = (string)r.Cells[0].Value;
                int count = (int)r.Cells[3].Value;
                float cPrice = (float)r.Cells[2].Value;
                DBFunc.addNewBuyRecord(bcode, count, cPrice);
            }
            SystemInfo sif = new SystemInfo("商品已成功入库");
            sif.ShowDialog();
            dataGridView2.Rows.Clear();
            updateBuyGridView();
        }


        /// <summary>
        /// 编辑完更新视图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void updateBuyGridView(object sender, DataGridViewCellEventArgs e)
        {
            updateBuyGridView();
        }
        #endregion



       
        #region 订单记录

        void showHistoryDetail(int order_id)
        {
            _db = new dbEntities();
            var sh = _db.salehistory.FirstOrDefault(c =>c.order_id == order_id && c.store_id == GlobalVariables.STORE_ID);
            var products = _db.vSaleHistoryDetails.Where(c => c.order_id == order_id);
            if (sh == null || products == null) return;
            this.vSaleHistoryDetailsBindingSource.DataSource = products;
            int all_count = products.Sum(c => (int?)c.product_count) ?? 0;
            if (sh.client_id == 0)
            {
                label19.Text = "会员:  " + "顾客";
                label20.Text = "电话:  " + "无";
            }
            else
            {
                var cl = _db.clients.FirstOrDefault(c => c.client_id == sh.client_id && c.client_storeid == GlobalVariables.STORE_ID);
                label19.Text = "会员:  " + cl.client_name;
                label20.Text = "电话:  " + cl.client_phone;
            }
            
            label7.Text = "件数:  " + all_count;
            label8.Text = "总额:  " + sh.order_amount;
            
        }
        void dataGridView3_CurrentCellChanged(object sender, EventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
            if (dgv.CurrentRow == null) return;
            dgv.CurrentRow.Selected = true;
            salehistory sh = (salehistory)dgv.CurrentRow.DataBoundItem;
            showHistoryDetail(sh.order_id);
        }


        void dataGridView6_DataSourceChanged(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        #endregion



        #region 系统设置绑定
        private void Bind_combox()
        {
            stores s = (stores)settings_name.SelectedItem;
            if (s == null) return;
            settings_address.Text = s.store_address;
            settings_phone.Text = s.store_phone;
        }

        private void updata_textbox(object sender, EventArgs e)
        {
            this.storesBindingSource.DataSource = _db.stores;
            stores s = (stores)settings_name.SelectedItem;
            s.store_address = settings_address.Text;
            s.store_phone = settings_phone.Text;
            GlobalVariables.STORE_ID = s.store_id;
             _db.SaveChanges();
             MessageBox.Show("Updata Success!");
        }

        private void settings_name_SelectedIndexChanged(object sender, EventArgs e)
        {
            Bind_combox();
        }
        #endregion

        #region 商品编辑
        /// <summary>
        /// 商品编辑输入框回车处理，筛选商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void textBox3_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != (Char)Keys.Enter) return;
            TextBox tb = (TextBox)sender;
            _db = new dbEntities();
            Int64 pid = 0;
            if (!Int64.TryParse(tb.Text, out pid))
            {
                this.vProductInfoBindingSource.DataSource = _db.vProductInfo;
            }
            else
            {
                this.vProductInfoBindingSource.DataSource = _db.vProductInfo.Where(c => c.product_id == pid ||
                    c.product_code.Contains(tb.Text) ||
                    c.product_code == tb.Text);
            }
            this.dataGridView5.Refresh();
        }


        void editProduct(object sender, DataGridViewCellEventArgs e)
        {
            _db = new dbEntities();
            DataGridView dgv = (DataGridView)sender;
            vProductInfo vpif = (vProductInfo) dgv.Rows[e.RowIndex].DataBoundItem;
            if(e.ColumnIndex == 2)
            {
                product_onsale pos = _db.product_onsale.FirstOrDefault(c => c.product_id == vpif.product_id);
                pos.sale_prices = (float)dgv[e.ColumnIndex, e.RowIndex].Value;
            }
            else if(e.ColumnIndex == 3)
            {
                product_onsale pos = _db.product_onsale.FirstOrDefault(c => c.product_id == vpif.product_id);
                pos.sale_prices = (int)dgv[e.ColumnIndex, e.RowIndex].Value;
            }
            else if(e.ColumnIndex == 1)
            {
                products_info pif = _db.products_info.FirstOrDefault(c => c.product_id == vpif.product_id);
                pif.product_name = (string)dgv[e.ColumnIndex, e.RowIndex].Value;
            }
            _db.SaveChanges();
        }

        #endregion

        #region 快捷键
        //重写处理命令键方法以监听快捷键
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F5)
            {
                CheckStock cs = new CheckStock();
                //System.Windows.Forms.SendKeys.Send("{F5}");
                cs.ShowDialog();
                return base.ProcessCmdKey(ref msg, keyData);
            }

            if (keyData == Keys.Enter)
            {
                //增添会员的确实按钮的回车快捷键

                if (this.main_tabcontrol.SelectedIndex == 1)
                {
                    this.button8.PerformClick();
                }
                return base.ProcessCmdKey(ref msg, keyData);
            }

            if (keyData == Keys.Space)
            {
                if (this.main_tabcontrol.SelectedIndex == 0)
                {
                    return true;
                }
            }
            
            //继续原来base.ProcessCmdKey中的处理
            return base.ProcessCmdKey(ref msg, keyData);
        }


        #endregion

        #region 用户信息窗口

        private void show_info(object sender, EventArgs e)
        {
            if (vcif == null)
            {
                return;
            }
            ClientInfo f = new ClientInfo(this.vcif);
            f.ShowDialog();
            updateClientInfo(usercode.Text);

        }

        #endregion


        private void textbox_MouseClick(object sender, MouseEventArgs e)
        {
            TextBox tb = (TextBox)sender;
            tb.SelectAll();
        }

        #region 客显部分
        /// <summary>
        /// 客显设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void settings_com_TextChanged(object sender, EventArgs e)
        {
            GlobalVariables.POS_PORT = settings_com.Text;
            pos = new CustomPos(GlobalVariables.POS_PORT);
        }

        /// <summary>
        /// 客显测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void button3_Click(object sender, EventArgs e)
        {
            pos.Display("8.8.8.8.8.8.8.8");
            pos.SetDisplayMode(CustomPos.DisplayMode.Total);
        }
        #endregion
        private void dataGridView5_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        void dataGridView3_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.ThrowException = false;
        }
    }
}
